import Snake from './Snake'
import ScorePanel from "./ScorePanel";

class GameControl {
  // 对蛇模块的控制
  snake: Snake
  // 用户按下的方向键 默认往右
  direction: string = 'ArrowRight'
  // 游戏是否正常运行的标识变量
  static isLive: boolean = true

  timer: any = null

  timeout: any = null

  time: number = 300

  constructor() {
    this.snake = new Snake()

    this.initGame()
  }

  // 初始化游戏界面  监测用户按键行为 蛇的前进等等
  initGame() {
    document.addEventListener('keyup', this.keyUpHandler.bind(this))
    GameControl.isLive && (this.timer = setTimeout(this.intervalCallback.bind(this), 300))
  }

  // 定时器内的回调函数
  intervalCallback() {
    this.snake.run(this.direction)
    this.time = 300 - (ScorePanel.level - 1) * 30
    clearTimeout(this.timer)
    if (!GameControl.isLive) return
    this.timer = setTimeout(this.intervalCallback.bind(this), this.time)
  }

  /** 监听键盘弹起事件处理回调
   * ArrowUp
     ArrowDown
     ArrowLeft
     ArrowRight
   * @param e
   */
  keyUpHandler(e: KeyboardEvent) {
    if (this.timeout !== null) {
      return
    }

    this.timeout = setTimeout(() => {
      // 将每次按下的键盘按钮与当前方向对比 禁止蛇掉头
      if (e.key === 'ArrowUp' || e.key === 'ArrowDown' || e.key === 'ArrowLeft' || e.key === "ArrowRight") {
        switch (this.direction) {
          case 'ArrowUp':
            if (e.key !== 'ArrowDown') this.modifyDirection(e.key)
            break
          case 'ArrowDown':
            if (e.key !== 'ArrowUp') this.modifyDirection(e.key)
            break
          case 'ArrowLeft':
            if (e.key !== 'ArrowRight') this.modifyDirection(e.key)
            break
          case 'ArrowRight':
            if (e.key !== 'ArrowLeft') this.modifyDirection(e.key)
            break
        }
      }
      this.timeout = null
    }, 120)
  }

  modifyDirection(directionName: string) {
    this.direction = directionName
  }
}

export default GameControl
